package com.haoji.upload.common.config.mvc;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haoji.upload.common.interceptor.CommonInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @program: upload
 * @description:
 * @author: xiaolei
 * @create: 2021-04-15 15:46
 **/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 自定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInterceptor()).excludePathPatterns("/static/*")
                .excludePathPatterns("/error").addPathPatterns("/**");
    }

    private HandlerInterceptor securityInterceptor(){
        return new CommonInterceptor();
    }

    /**
     * 类型装换器
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new com.haoji.upload.common.Value.mvc.StringToDateConverter());
    }

    /**
     * 返回值Json格式化处理
     * @param converters
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = new com.haoji.upload.common.Value.mvc.CustomObjectMapper();
                objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
                ((MappingJackson2HttpMessageConverter)converter).setObjectMapper(objectMapper);
            }
        }
    }

}
